package com.itheima.travel.service.impl;

import com.itheima.travel.mapper.UserMapper;
import com.itheima.travel.pojo.User;
import com.itheima.travel.pojo.UserExample;
import com.itheima.travel.req.UserVo;
import com.itheima.travel.service.UserService;
import com.itheima.travel.session.SubjectUser;
import com.itheima.travel.session.SubjectUserContext;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.EmptyUtil;
import com.itheima.travel.utils.MD5Coder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SubjectUserContext subjectUserContext;

    /**
     * 用户注册
     *
     * @param userVo
     * @return
     */
    @Override
    public Boolean registerUser(UserVo userVo) {
        User user = BeanConv.toBean(userVo, User.class);
        user.setPassword(MD5Coder.md5Encode(user.getPassword()));
        System.out.println("转换后的user对象" + user);
        int flag = userMapper.insert(user);
        return flag>0;
    }

    /**
     * 用户登录
     * @param userVo
     * @return
     */
    @Override
    public UserVo loginUser(UserVo userVo) {
        //组装查询条件
        UserExample userExample = new UserExample();
        //使用代码生成器制定的标准
        userExample.createCriteria().andUsernameEqualTo(userVo.getUsername())
                .andPasswordEqualTo(MD5Coder.md5Encode(userVo.getPassword()));
        List<User> users = userMapper.selectByExample(userExample);
        UserVo resultVo = null;
        if(users.size()==1){
            User user = users.get(0);
            resultVo = BeanConv.toBean(user, UserVo.class);
            String token = UUID.randomUUID().toString();
            resultVo.setToken(token);
            SubjectUser subjectUser = BeanConv.toBean(resultVo, SubjectUser.class);
            subjectUserContext.createdSubject(token,subjectUser);
        }
        return resultVo;
    }

    @Override
    public void loginOutUser() {
        subjectUserContext.deleteSubject();
    }

    @Override
    public Boolean isLogin() {
        SubjectUser subject = subjectUserContext.getSubject();
        if (!EmptyUtil.isNullOrEmpty(subject)){
            return true;
        }
//        return subjectUserContext.existSubject();
        return false;
    }
}
